<template>
  <div class="shopping-cart i_car">
    <div class="car_t" @click="toggleCart">
      购物车 [ <span>{{ totalItems }}</span> ]
    </div>
    <div class="car_bg" v-show="showCart">
      <!-- 未登录状态 -->
      <div class="un_login" v-if="!isLoggedIn">
        还未登录！<router-link to="/login" class="text-primary">马上登录</router-link> 查看购物车！
      </div>
      
      <!-- 已登录状态 -->
      <div v-else>
        <ul class="cars" v-if="cartItems.length > 0">
          <li v-for="item in cartItems" :key="item.productId">
            <div class="img">
              <router-link :to="`/product/${item.productId}`">
                <img 
                  :src="getProductImage(item)" 
                  :alt="item.productName" 
                  @error="handleImageError"
                />
              </router-link>
            </div>
            <div class="name">
              <router-link :to="`/product/${item.productId}`">{{ item.productName }}</router-link>
            </div>
            <div class="price">
              <span class="text-primary">{{ formatPrice(item.price) }}</span> X{{ item.quantity }}
            </div>
          </li>
        </ul>
        
        <div class="empty-cart" v-else>
          <p>购物车是空的</p>
          <router-link to="/products" class="btn btn-primary">去购物</router-link>
        </div>
        
        <div class="price_sum" v-if="cartItems.length > 0">
          共计 <span class="text-primary">￥</span><span>{{ totalPrice }}</span>
        </div>
        <div class="price_a" v-if="cartItems.length > 0">
          <router-link to="/cart">去购物车结算</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { formatPrice } from '@/utils'
import { getCart } from '@/api/cartApi'

export default {
  name: 'ShoppingCart',
  props: {
    isLoggedIn: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showCart: false,
      cartItems: []
    }
  },
  computed: {
    totalItems() {
      return this.cartItems.reduce((total, item) => total + item.quantity, 0)
    },
    totalPrice() {
      const total = this.cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0)
      return total.toFixed(2)
    }
  },
  methods: {
    formatPrice,
    // 获取商品图片
    getProductImage(product) {
      if (product.image) {
        try {
          // 尝试返回实际图片路径
          return require(`@/assets/files/${product.image}`)
        } catch (error) {
          // 如果图片不存在，返回默认图片
          console.warn(`商品图片加载失败: ${product.image}`, error)
          return require('@/assets/images/default_product.jpg')
        }
      }
      // 如果没有image，返回默认图片
      return require('@/assets/images/default_product.jpg')
    },
    
    toggleCart() {
      this.showCart = !this.showCart
      // 当展开购物车时，如果已登录则获取购物车数据
      if (this.showCart && this.isLoggedIn) {
        this.fetchCartData()
      }
    },
    // 图片加载错误处理
    handleImageError(event) {
      event.target.src = require('@/assets/images/default_product.jpg')
    },
    // 获取购物车数据
    async fetchCartData() {
      try {
        const res = await getCart()
        if (Array.isArray(res)) {
          this.cartItems = res.map(item => ({
            productId: item.productId,
            productName: item.productName,
            price: item.price,
            quantity: item.quantity,
            image: item.image
          }))
        } else {
          this.cartItems = []
        }
        // 触发事件通知其他组件购物车已更新
        this.$emit('cart-updated', this.cartItems)
      } catch (error) {
        console.error('获取购物车数据失败:', error)
        this.cartItems = []
      }
    },
    // 添加商品到购物车（供外部调用）
    async addToCart(product) {
      // 这里可以调用API添加商品到购物车
      // 由于是公共组件，实际的添加操作应该在商品详情页完成
      // 这里只更新本地显示
      await this.fetchCartData()
    },
    handleClickOutside(event) {
      if (!this.$el.contains(event.target)) {
        this.showCart = false
      }
    }
  },
  mounted() {
    document.addEventListener('click', this.handleClickOutside)
    // 监听购物车更新事件
    window.addEventListener('cart-updated', this.fetchCartData)
  },
  beforeUnmount() {
    document.removeEventListener('click', this.handleClickOutside)
    // 移除事件监听
    window.removeEventListener('cart-updated', this.fetchCartData)
  }
}
</script>

<style scoped>
.empty-cart {
  text-align: center;
  padding: 20px;
}

.empty-cart p {
  margin-bottom: 15px;
  color: #666;
}

.shopping-cart {
  position: relative;
}

.img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.img {
  width: 60px;
  height: 60px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>